<template>
  <div class="hanjie-gongyi-page">
    <div class="table1_container">
      <div class="table1_dataShower" style="padding-bottom: 50px; padding-top: 50px; box-sizing: border-box">
        <button class="report-top-button" @click="back">返回上级页面</button>
        <button class="report-top-button" @click="openFieldDialog">选择字段</button>
        <button class="report-top-button" @click="printReport">报表打印</button>
      <div style="text-align: center; margin: 10px 0;">
        <div style="display: inline-flex; gap: 20px;">
          <!-- 未完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffffff; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>未完成</span>
          </div>

          <!-- 已完成 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #e6f7e6; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>已完成</span>
          </div>

          <!-- 不合格重采 -->
          <div style="display: flex; align-items: center;">
            <div
              style="width: 16px; height: 16px; background-color: #ffebeb; border: 1px solid #ddd; margin-right: 5px;"
            />
            <span>不合格重采</span>
          </div>
        </div>
      </div>
      <h1>钢筋焊接（工艺）试验报告汇总表</h1>
      <!-- 基本信息部分 - 在表格上方 -->
      <div style="width:90%;margin:0 auto;display: flex">
        <div style="text-align: left">
          <span>工程名称:</span>
          <span>{{ projectName + '  ' + subprojectName }}</span>
        </div>
        <div style="margin-left: 1800px">
          <span>共{{ 'XXX' }}页</span>
          <span>第{{ 'XXX' }}页</span>
        </div>
      </div>
      <table class="wendu-table1_top_table">
        <tr>
          <template v-for="field in visibleFields">
            <td
              v-if="field.type === 'group'"
              :key="'header-group-' + field.key"
              :colspan="fieldColspan(field)"
            >
              {{ field.label }}
            </td>
            <td
              v-else
              :key="'header-' + field.key"
              :rowspan="2"
              :colspan="field.colspan || 1"
            >
              {{ field.label }}
            </td>
          </template>
        </tr>
        <tr v-if="visibleGroupFields.length">
          <template v-for="field in visibleGroupFields">
            <template v-for="child in field.children">
              <td
                v-if="child.columns && child.columns.length"
                :key="'subheader-' + field.key + '-' + child.key"
                :colspan="child.columns.length"
              >
                {{ child.label }}
              </td>
            </template>
          </template>
        </tr>
        <tr v-for="(item, index) in reportData" :key="index">
          <template v-for="field in visibleFields">
            <template v-if="field.type === 'group'">
              <template v-for="child in field.children">
                <template v-for="(column, colIndex) in child.columns">
                  <td :key="field.key + '-' + child.key + '-' + index + '-' + colIndex">
                    {{ column.getValue(item, colIndex) }}
                  </td>
                </template>
              </template>
            </template>
            <template v-else>
              <td
                :key="field.key + '-' + index"
                :colspan="field.colspan || 1"
              >
                {{ getFieldDisplayValue(field, item) }}
              </td>
            </template>
          </template>
        </tr>
        <tr>
          <td :colspan="totalColumns" style="text-align: left">
            说明：在检验不合格后又重新取样检验合格的，两次检验结果都必须统计在汇总表中。
          </td>
        </tr>
      </table>
      <div style="text-align: left; width: 90%;margin: 0 auto;display: flex">
        <div>施工单位项目技术负责人：{{ 'XXX' }}</div>
        <div style="margin-left: 10%">总监理工程师(建设单位项目技术负责人)：{{ 'XXX' }}</div>
        <div style="margin-left: 10%">（监理项目部章）</div>
        <div style="margin-left: 10%">填表人：{{ 'XXX' }}</div>
      </div>
    </div>
  </div>

    <el-dialog
      title="选择显示字段"
      :visible.sync="fieldDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          style="margin-bottom: 15px;"
        >
          全选
        </el-checkbox>
        <el-divider></el-divider>
        <el-checkbox-group v-model="selectedFields" @change="handleCheckedFieldsChange" class="field-checkbox-group">
          <div
            v-for="field in allFields"
            :key="field.key"
            style="margin-bottom: 10px;"
          >
            <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmFieldSelection">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

/*
 *    这个报表真麻烦！！！
 *
 */

import { getWeldTablePreview } from '@/api/statementManage/xianChang/xianChang'

export default {
  data() {
    return {
      localStorageId: '',
      reportData: {},
      previewData: {},
      projectName: '',
      subprojectName: '',
      fieldDialogVisible: false,
      checkAll: true,
      isIndeterminate: false,
      selectedFields: [],
      allFields: [
        { key: 'batch', label: '批次', colspan: 1, getValue: item => item.dataId },
        { key: 'producer', label: '生产厂家', colspan: 1, getValue: item => item.producer },
        { key: 'steelType', label: '钢筋牌号', colspan: 1, getValue: item => item.steelType },
        { key: 'weldType', label: '焊接类型', colspan: 1, getValue: item => item.weldType },
        { key: 'representAmount', label: '代表数量', colspan: 1, getValue: item => item.representAmount },
        { key: 'usePart', label: '使用部位', colspan: 1, getValue: item => item.usePart },
        { key: 'checkDate', label: '收样日期', colspan: 1, getValue: item => item.checkDate },
        { key: 'reportDate', label: '试验日期', colspan: 1, getValue: item => item.reportDate },
        { key: 'reportNumber', label: '试验报告', colspan: 1, getValue: item => item.reportNumber },
        { key: 'diameter', label: '直径或横截面尺寸(mm)', colspan: 1, getValue: item => item.diameter },
        { key: 'connectorArea', label: '横截面积 (mm2）', colspan: 1, getValue: item => item.connectorArea },
        {
          key: 'mechanicsGroup',
          label: '力学性能',
          type: 'group',
          children: [
            {
              key: 'pullStrengths',
              label: '抗拉',
              columns: [
                { getValue: item => item.pullStrengths && item.pullStrengths[0] },
                { getValue: item => item.pullStrengths && item.pullStrengths[1] },
                { getValue: item => item.pullStrengths && item.pullStrengths[2] }
              ]
            },
            {
              key: 'breakPositions',
              label: '断裂位置',
              columns: [
                { getValue: item => item.breakPositions && item.breakPositions[0] },
                { getValue: item => item.breakPositions && item.breakPositions[1] },
                { getValue: item => item.breakPositions && item.breakPositions[2] }
              ]
            },
            {
              key: 'breakFeatures',
              label: '断裂特征',
              columns: [
                { getValue: item => item.breakFeatures && item.breakFeatures[0] },
                { getValue: item => item.breakFeatures && item.breakFeatures[1] },
                { getValue: item => item.breakFeatures && item.breakFeatures[2] }
              ]
            }
          ]
        },
        {
          key: 'bendingGroup',
          label: '弯曲性能',
          type: 'group',
          children: [
            {
              key: 'bendingDiameters',
              label: '弯心压头直径',
              columns: [
                { getValue: item => item.bendingDiameters && item.bendingDiameters[0] },
                { getValue: item => item.bendingDiameters && item.bendingDiameters[1] },
                { getValue: item => item.bendingDiameters && item.bendingDiameters[2] }
              ]
            },
            {
              key: 'bendingAngles',
              label: '弯曲',
              columns: [
                { getValue: item => item.bendingAngles && item.bendingAngles[0] },
                { getValue: item => item.bendingAngles && item.bendingAngles[1] },
                { getValue: item => item.bendingAngles && item.bendingAngles[2] }
              ]
            },
            {
              key: 'bendingResults',
              label: '结果',
              columns: [
                { getValue: item => item.bendingResults && item.bendingResults[0] },
                { getValue: item => item.bendingResults && item.bendingResults[1] },
                { getValue: item => item.bendingResults && item.bendingResults[2] }
              ]
            }
          ]
        },
        { key: 'conclusion', label: '结论', colspan: 1, getValue: item => item.conclusion },
        { key: 'projectName', label: '项目名称', colspan: 1, getValue: (item, vm) => vm.projectName },
        { key: 'subprojectName', label: '单位工程', colspan: 1, getValue: (item, vm) => vm.subprojectName },
        { key: 'checkMethod', label: '检验型式', colspan: 1, getValue: item => item.checkMethod },
        { key: 'connectorType', label: '接头类型', colspan: 1, getValue: item => item.connectorType },
        { key: 'yanshouRule', label: '验收规范', colspan: 1, getValue: item => item.yanshouRule },
        { key: 'projectNumber', label: '工程号', colspan: 1, getValue: item => item.projectNumber },
        { key: 'superviseNumber', label: '监督号', colspan: 1, getValue: item => item.superviseNumber },
        { key: 'checkCompany', label: '检测单位', colspan: 1, getValue: item => item.checkCompany },
        { key: 'delegateCompany', label: '委托单位', colspan: 1, getValue: item => item.delegateCompany },
        { key: 'delegateNumber', label: '委托编号', colspan: 1, getValue: item => item.delegateNumber },
        { key: 'witnessCompany', label: '见证单位', colspan: 1, getValue: item => item.witnessCompany },
        { key: 'witnessPerson', label: '见证人', colspan: 1, getValue: item => item.witnessPerson },
        { key: 'sendPerson', label: '送样人', colspan: 1, getValue: item => item.sendPerson },
        { key: 'checkType', label: '检验类别', colspan: 1, getValue: item => item.checkType },
        { key: 'jiansheCompany', label: '建设单位', colspan: 1, getValue: item => item.jiansheCompany },
        { key: 'shigongCompany', label: '施工单位', colspan: 1, getValue: item => item.shigongCompany }
      ]
    }
  },
  created() {
    this.selectedFields = this.allFields.map(field => field.key)
  },
  computed: {
    visibleFields() {
      return this.allFields.filter(field => this.selectedFields.includes(field.key))
    },
    visibleGroupFields() {
      return this.visibleFields.filter(field => field.type === 'group')
    },
    totalColumns() {
      return this.visibleFields.reduce((sum, field) => sum + this.fieldColspan(field), 0)
    }
  },
  async mounted() { // 钩子函数
    const sessionData = sessionStorage.getItem('tempObj1')

    const parseData = JSON.parse(sessionData)
    this.projectName = parseData.projectName
    this.subprojectName = parseData.subprojectName
    const subprojectId = parseData.subprojectId

    const { result } = await getWeldTablePreview(subprojectId, '工艺检')

    this.reportData = result
    console.log(JSON.stringify(result))
  },
  beforeDestroy() { // 离开页面要做的事
    // 那就是清除localstorage！！！
    if (this.localStorageId) {
      localStorage.removeItem(this.localStorageId)
    }
    document.querySelector('body').setAttribute('style', 'background-color: white;') // 还原，因为这是个全局样式
  },
  beforeCreate() {
    document.querySelector('body').setAttribute('style', 'background-color:#f5f5f5;') // 设置对比色
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    openFieldDialog() {
      this.fieldDialogVisible = true
    },
    handleCheckAllChange(val) {
      if (val) {
        this.selectedFields = this.allFields.map(f => f.key)
      } else {
        this.selectedFields = []
      }
      this.isIndeterminate = false
    },
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.allFields.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allFields.length
    },
    confirmFieldSelection() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请至少选择一个字段！')
        return
      }
      this.fieldDialogVisible = false
      this.handleCheckedFieldsChange(this.selectedFields)
      this.$message.success('字段选择已更新！')
    },
    fieldColspan(field) {
      if (field.type === 'group') {
        return field.children.reduce((sum, child) => sum + child.columns.length, 0)
      }
      return field.colspan || 1
    },
    getFieldDisplayValue(field, item) {
      if (typeof field.getValue === 'function') {
        return field.getValue(item, this) || ''
      }
      return item[field.key] || ''
    },
    printReport() {
      window.print()
    }
  }
}
</script>

<style>

/*
先来设置每个任务项对应的背景颜色吧！
 */
.row-unfinished {
  background-color: #ffffff; /* 未完成 - 白色或默认色 */
}

.row-finished {
  background-color: #e6f7e6; /* 已完成 - 浅绿色 */
}

.row-failed {
  background-color: #ffebeb; /* 不合格重采 - 浅红色 */
}

.table1_container {
  width: 4500px;
  background: white;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  padding-bottom: 20px;
}

.table1_dataShower {
  width: 80%;
  background: white;
  margin: 0 auto;
  border: 2px black solid;
}

/*这是返回按钮的样式*/
.report-top-button {
  display: block;
  margin: 0 auto;
  margin-bottom: 20px;
  padding: 12px 28px;
  font-size: 16px;
  font-weight: 600;
  font-family: 'Arial', sans-serif;
  color: #ffffff;
  background: linear-gradient(90deg, #1e3a8a, #3b82f6); /* 建筑行业蓝色调，稳重且有活力 */
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.report-top-button:hover {
  background: linear-gradient(90deg, #1e3a8a, #2563eb);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.report-top-button:active {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  transform: translateY(0);
}

/*表格样式*/
.wendu-table1_top_table {
  width: 90%;
  margin: 0 auto;
  border-collapse: collapse;
  border: 1px solid black;
  table-layout: fixed;
}

/*表格的样式*/
.wendu-table1_top_table tr td {
  height: 50px;
  border: 1px solid black;
  word-wrap: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word; /* 更现代的换行属性 */
}

#table1_top_table_last_col {
  width: 20%;
  min-height: 50px;
}

th {
  box-sizing: border-box !important;
}

@media print {
  @page {
    size: A4 landscape;
    margin-left: 15mm;
    margin-right: 15mm;
  }
}

.field-checkbox-group {
  text-align: left;
}

.field-checkbox-group .el-checkbox {
  width: 100%;
}
</style>

